const { prisma } = require('../config/prisma');

class ListingPrisma {
  // 状态值映射：中文 -> 英文枚举
  static STATUS_MAP = {
    '在售': 'ON_SALE',
    '已售': 'SOLD',
    '下架': 'OFF_SHELF'
  };

  // 反向状态值映射：英文枚举 -> 中文
  static STATUS_REVERSE_MAP = {
    'ON_SALE': '在售',
    'SOLD': '已售',
    'OFF_SHELF': '下架'
  };

  // 商品类型映射：中文 -> 英文枚举
  static TYPE_MAP = {
    '公司': 'COMPANY',
    '个体户': 'INDIVIDUAL',
    '代账户': 'ACCOUNTING'
  };

  // 反向商品类型映射：英文枚举 -> 中文
  static TYPE_REVERSE_MAP = {
    'COMPANY': '公司',
    'INDIVIDUAL': '个体户',
    'ACCOUNTING': '代账户'
  };

  // 注册资本范围映射：中文 -> 英文枚举
  static CAPITAL_RANGE_MAP = {
    '10万以下': 'UNDER_100K',
    '10-50万': 'FROM_100K_TO_500K',
    '50-100万': 'FROM_500K_TO_1M',
    '100-500万': 'FROM_1M_TO_5M',
    '500-1000万': 'FROM_5M_TO_10M',
    '1000万以上': 'OVER_10M'
  };

  // 反向注册资本范围映射：英文枚举 -> 中文
  static CAPITAL_RANGE_REVERSE_MAP = {
    'UNDER_100K': '10万以下',
    'FROM_100K_TO_500K': '10-50万',
    'FROM_500K_TO_1M': '50-100万',
    'FROM_1M_TO_5M': '100-500万',
    'FROM_5M_TO_10M': '500-1000万',
    'OVER_10M': '1000万以上'
  };

  // 实缴状态映射：中文 -> 英文枚举
  static PAID_STATUS_MAP = {
    '已实缴': 'PAID',
    '未实缴': 'UNPAID',
    '不确定': 'UNCERTAIN'
  };

  // 反向实缴状态映射：英文枚举 -> 中文
  static PAID_STATUS_REVERSE_MAP = {
    'PAID': '已实缴',
    'UNPAID': '未实缴',
    'UNCERTAIN': '不确定'
  };

  // 公司类型映射：中文 -> 英文枚举
  static COMPANY_TYPE_MAP = {
    '普通公司': 'NORMAL',
    '国家局公司': 'NATIONAL',
    '上市公司': 'LISTED',
    '不确定': 'UNCERTAIN'
  };

  // 反向公司类型映射：英文枚举 -> 中文
  static COMPANY_TYPE_REVERSE_MAP = {
    'NORMAL': '普通公司',
    'NATIONAL': '国家局公司',
    'LISTED': '上市公司',
    'UNCERTAIN': '不确定'
  };

  // 审核状态映射：中文 -> 英文枚举
  static AUDIT_STATUS_MAP = {
    '待审核': 'PENDING',
    '已通过': 'APPROVED',
    '已拒绝': 'REJECTED'
  };

  // 反向审核状态映射：英文枚举 -> 中文
  static AUDIT_STATUS_REVERSE_MAP = {
    'PENDING': '待审核',
    'APPROVED': '已通过',
    'REJECTED': '已拒绝'
  };

  // 税务状态映射：中文 -> 英文枚举
  static TAX_STATUS_MAP = {
    '未登记': 'UNREGISTERED',
    '小规模': 'SMALL_SCALE',
    '一般纳税人': 'GENERAL_TAXPAYER',
    '未开业': 'NOT_OPENED',
    '不确定': 'UNCERTAIN'
  };

  // 反向税务状态映射：英文枚举 -> 中文
  static TAX_STATUS_REVERSE_MAP = {
    'UNREGISTERED': '未登记',
    'SMALL_SCALE': '小规模',
    'GENERAL_TAXPAYER': '一般纳税人',
    'NOT_OPENED': '未开业',
    'UNCERTAIN': '不确定'
  };

  // 银行开户状态映射：中文 -> 英文枚举
  static BANK_STATUS_MAP = {
    '已开户': 'OPENED',
    '未开户': 'NOT_OPENED',
    '不确定': 'UNCERTAIN'
  };

  // 反向银行开户状态映射：英文枚举 -> 中文
  static BANK_STATUS_REVERSE_MAP = {
    'OPENED': '已开户',
    'NOT_OPENED': '未开户',
    'UNCERTAIN': '不确定'
  };



  // 纳税等级映射：中文 -> 英文枚举
  static TAX_GRADE_MAP = {
    'A': 'GRADE_A',
    'B': 'GRADE_B',
    'M': 'GRADE_M',
    'C': 'GRADE_C',
    'D': 'GRADE_D',
    '未开通': 'NOT_OPENED'
  };

  // 反向纳税等级映射：英文枚举 -> 中文
  static TAX_GRADE_REVERSE_MAP = {
    'GRADE_A': 'A',
    'GRADE_B': 'B',
    'GRADE_M': 'M',
    'GRADE_C': 'C',
    'GRADE_D': 'D',
    'NOT_OPENED': '未开通'
  };
  constructor(data) {
    this.id = data.id;
    this.user_id = data.user_id;
    this.listing_type = data.listing_type;
    this.company_name = data.company_name;
    this.status = data.status;
    this.price = data.price;
    this.is_negotiable = data.is_negotiable;
    this.registration_province = data.registration_province;
    this.registration_city = data.registration_city;
    this.establishment_date = data.establishment_date;
    this.registered_capital_range = data.registered_capital_range;
    this.paid_in_status = data.paid_in_status;
    this.company_type = data.company_type;
    this.tax_status = data.tax_status;
    this.tax_grade = data.tax_grade;
    this.bank_account_status = data.bank_account_status;
    this.has_trademark = data.has_trademark;
    this.has_patent = data.has_patent;
    this.has_software_copyright = data.has_software_copyright;
    this.has_license_plate = data.has_license_plate;
    this.has_social_security = data.has_social_security;
    this.bank_flow = data.bank_flow;
    this.has_bidding_history = data.has_bidding_history;
    this.description = data.description;
    this.expires_at = data.expires_at;
    // 审核相关字段
    this.audit_status = data.audit_status;
    this.audit_admin_id = data.audit_admin_id;
    this.audit_time = data.audit_time;
    this.audit_comment = data.audit_comment;
    this.auto_publish_at = data.auto_publish_at;
    this.created_at = data.created_at;
    this.updated_at = data.updated_at;

    // 关联的用户信息（如果有）
    this.publisher_nickname = data.users?.nickname || data.publisher_nickname;
    this.users = data.users; // 完整的用户对象
    this.audit_admin = data.administrators; // 审核管理员信息
  }

  /**
   * 创建新的挂牌信息
   * @param {Object} listingData 挂牌信息数据
   * @returns {Promise<ListingPrisma>}
   */
  static async create(listingData) {
    // 处理日期字段
    const processedData = { ...listingData };
    if (processedData.establishment_date && typeof processedData.establishment_date === 'string') {
      processedData.establishment_date = new Date(processedData.establishment_date);
    }
    if (processedData.expires_at && typeof processedData.expires_at === 'string') {
      processedData.expires_at = new Date(processedData.expires_at);
    }

    const listing = await prisma.listings.create({
      data: {
        user_id: BigInt(processedData.user_id),
        listing_type: this.TYPE_MAP[processedData.listing_type] || processedData.listing_type,
        company_name: processedData.company_name,
        status: this.STATUS_MAP[processedData.status] || processedData.status || 'ON_SALE',
        price: processedData.is_negotiable ? null : (processedData.price || null),
        is_negotiable: processedData.is_negotiable || false,
        registration_province: processedData.registration_province || null,
        registration_city: processedData.registration_city || null,
        establishment_date: processedData.establishment_date || null,
        registered_capital_range: this.CAPITAL_RANGE_MAP[processedData.registered_capital_range] || processedData.registered_capital_range || null,
        paid_in_status: this.PAID_STATUS_MAP[processedData.paid_in_status] || processedData.paid_in_status || null,
        company_type: this.COMPANY_TYPE_MAP[processedData.company_type] || processedData.company_type || null,
        tax_status: this.TAX_STATUS_MAP[processedData.tax_status] || processedData.tax_status || null,
        tax_grade: this.TAX_GRADE_MAP[processedData.tax_grade] || processedData.tax_grade || null,
        bank_account_status: this.BANK_STATUS_MAP[processedData.bank_account_status] || processedData.bank_account_status || null,
        has_trademark: processedData.has_trademark || false,
        has_patent: processedData.has_patent || false,
        has_software_copyright: processedData.has_software_copyright || false,
        has_license_plate: processedData.has_license_plate || false,
        has_social_security: processedData.has_social_security || false,
        bank_flow: processedData.bank_flow || null,
        has_bidding_history: processedData.has_bidding_history || false,
        description: processedData.description || null,
        expires_at: processedData.expires_at || null,
        // 审核相关字段
        audit_status: this.AUDIT_STATUS_MAP[processedData.audit_status] || processedData.audit_status || 'PENDING',
        audit_admin_id: processedData.audit_admin_id || null,
        audit_time: processedData.audit_time || null,
        audit_comment: processedData.audit_comment || null,
        auto_publish_at: processedData.auto_publish_at || null
      },
      include: {
        users: {
          select: {
            id: true,
            nickname: true,
            avatar_url: true,
            phone_number: true
          }
        },
        administrators: true
      }
    });
    return new ListingPrisma(listing);
  }

  /**
   * 根据ID查找挂牌信息
   * @param {number} id 挂牌信息ID
   * @returns {Promise<ListingPrisma|null>}
   */
  static async findById(id) {
    const listing = await prisma.listings.findUnique({
      where: { id: BigInt(id) },
      include: {
        users: {
          select: {
            id: true,
            nickname: true,
            avatar_url: true,
            phone_number: true
          }
        },
        administrators: true
      }
    });
    return listing ? new ListingPrisma(listing) : null;
  }

  /**
   * 获取挂牌信息列表（分页）
   * @param {Object} options 查询选项
   * @returns {Promise<Object>}
   */
  static async getList(options = {}) {
    const {
      page = 1,
      pageSize = 10,
      status,  // 移除默认值，让前端控制
      listing_type,
      registration_province,
      registration_city,
      company_type,
      tax_status,
      search
    } = options;

    const pageNum = parseInt(page);
    const pageSizeNum = parseInt(pageSize);
    const skip = (pageNum - 1) * pageSizeNum;

    // 构建where条件
    const where = {};

    // 转换状态值 - 只有当status存在且不为空字符串时才过滤
    if (status && status.trim() !== '') {
      where.status = this.STATUS_MAP[status] || status;
    }

    // 转换商品类型
    if (listing_type) {
      where.listing_type = this.TYPE_MAP[listing_type] || listing_type;
    }

    // 省份筛选
    if (registration_province) {
      where.registration_province = registration_province;
    }

    // 城市筛选
    if (registration_city) {
      where.registration_city = registration_city;
    }
    
    if (company_type) {
      where.company_type = company_type;
    }
    
    if (tax_status) {
      where.tax_status = tax_status;
    }
    
    if (search) {
      where.OR = [
        { company_name: { contains: search } },
        { description: { contains: search } }
      ];
    }

    // 并行查询总数和列表数据
    const [total, listings] = await Promise.all([
      prisma.listings.count({ where }),
      prisma.listings.findMany({
        where,
        include: {
          users: {
            select: {
              id: true,
              nickname: true,
              avatar_url: true,
              phone_number: true
            }
          }
        },
        orderBy: { created_at: 'desc' },
        skip,
        take: pageSizeNum
      })
    ]);

    return {
      data: listings.map(listing => new ListingPrisma(listing)),
      pagination: {
        page: pageNum,
        pageSize: pageSizeNum,
        total,
        totalPages: Math.ceil(total / pageSizeNum)
      }
    };
  }

  /**
   * 获取用户发布的挂牌信息
   * @param {number} userId 用户ID
   * @param {Object} options 查询选项
   * @returns {Promise<Object>}
   */
  static async getUserListings(userId, options = {}) {
    const { page = 1, pageSize = 10, status, audit_status } = options;
    const pageNum = parseInt(page);
    const pageSizeNum = parseInt(pageSize);
    const skip = (pageNum - 1) * pageSizeNum;

    const where = {
      user_id: BigInt(userId)
    };

    // 转换状态值：中文 -> 英文枚举
    if (status) {
      where.status = this.STATUS_MAP[status] || status;
    }

    // 转换审核状态值：中文 -> 英文枚举
    if (audit_status) {
      where.audit_status = this.AUDIT_STATUS_MAP[audit_status] || audit_status;
    }

    const [total, listings, stats] = await Promise.all([
      prisma.listings.count({ where }),
      prisma.listings.findMany({
        where,
        orderBy: { created_at: 'desc' },
        skip,
        take: pageSizeNum
      }),
      // 获取用户的统计数据（不受筛选条件影响）
      this.getUserListingsStats(userId)
    ]);

    return {
      data: listings.map(listing => new ListingPrisma(listing)),
      pagination: {
        page: pageNum,
        pageSize: pageSizeNum,
        total,
        totalPages: Math.ceil(total / pageSizeNum)
      },
      stats
    };
  }

  /**
   * 获取用户发布信息的统计数据
   * @param {number} userId 用户ID
   * @returns {Promise<Object>}
   */
  static async getUserListingsStats(userId) {
    const baseWhere = {
      user_id: BigInt(userId)
    };

    const [totalCount, sellingCount, soldCount, offShelfCount] = await Promise.all([
      // 总发布数
      prisma.listings.count({ where: baseWhere }),
      // 在售数量
      prisma.listings.count({ 
        where: { 
          ...baseWhere, 
          status: this.STATUS_MAP['在售'] 
        } 
      }),
      // 已售数量
      prisma.listings.count({ 
        where: { 
          ...baseWhere, 
          status: this.STATUS_MAP['已售'] 
        } 
      }),
      // 下架数量
      prisma.listings.count({ 
        where: { 
          ...baseWhere, 
          status: this.STATUS_MAP['下架'] 
        } 
      })
    ]);

    return {
      total: totalCount,
      selling: sellingCount,
      sold: soldCount,
      off_shelf: offShelfCount
    };
  }

  /**
   * 更新挂牌信息
   * @param {number} id 挂牌信息ID
   * @param {Object} updateData 更新数据
   * @returns {Promise<ListingPrisma>}
   */
  static async update(id, updateData) {
    // 处理BigInt字段
    const data = { ...updateData };
    if (data.user_id !== undefined) {
      data.user_id = BigInt(data.user_id);
    }

    // 转换枚举值
    if (data.listing_type !== undefined) {
      data.listing_type = this.TYPE_MAP[data.listing_type] || data.listing_type;
    }
    if (data.status !== undefined) {
      data.status = this.STATUS_MAP[data.status] || data.status;
    }
    if (data.registered_capital_range !== undefined) {
      data.registered_capital_range = this.CAPITAL_RANGE_MAP[data.registered_capital_range] || data.registered_capital_range;
    }
    if (data.paid_in_status !== undefined) {
      data.paid_in_status = this.PAID_STATUS_MAP[data.paid_in_status] || data.paid_in_status;
    }
    if (data.company_type !== undefined) {
      data.company_type = this.COMPANY_TYPE_MAP[data.company_type] || data.company_type;
    }
    if (data.tax_status !== undefined) {
      data.tax_status = this.TAX_STATUS_MAP[data.tax_status] || data.tax_status;
    }
    if (data.tax_grade !== undefined) {
      data.tax_grade = this.TAX_GRADE_MAP[data.tax_grade] || data.tax_grade;
    }
    if (data.bank_account_status !== undefined) {
      data.bank_account_status = this.BANK_STATUS_MAP[data.bank_account_status] || data.bank_account_status;
    }
    if (data.audit_status !== undefined) {
      data.audit_status = this.AUDIT_STATUS_MAP[data.audit_status] || data.audit_status;
    }

    // 处理价格字段 - 如果设置为面议，确保price为null
    if (data.is_negotiable === true) {
      data.price = null;
    }

    // 处理日期字段
    if (data.establishment_date !== undefined && data.establishment_date && typeof data.establishment_date === 'string') {
      data.establishment_date = new Date(data.establishment_date);
    }
    if (data.expires_at !== undefined && data.expires_at && typeof data.expires_at === 'string') {
      data.expires_at = new Date(data.expires_at);
    }

    const listing = await prisma.listings.update({
      where: { id: BigInt(id) },
      data,
      include: {
        users: {
          select: {
            id: true,
            nickname: true,
            avatar_url: true,
            phone_number: true
          }
        }
      }
    });
    return new ListingPrisma(listing);
  }

  /**
   * 删除挂牌信息
   * @param {number} id 挂牌信息ID
   * @returns {Promise<boolean>}
   */
  static async delete(id) {
    await prisma.listings.delete({
      where: { id: BigInt(id) }
    });
    return true;
  }

  /**
   * 更新挂牌状态
   * @param {number} id 挂牌信息ID
   * @param {string} status 新状态
   * @returns {Promise<ListingPrisma>}
   */
  static async updateStatus(id, status) {
    return await ListingPrisma.update(id, { status });
  }

  /**
   * 审核通过
   * @param {number} id 挂牌信息ID
   * @param {number} adminId 管理员ID
   * @param {string} comment 审核备注
   * @returns {Promise<ListingPrisma>}
   */
  static async approve(id, adminId, comment = null) {
    // 先查询当前状态，检查用户是否已主动下架
    const currentListing = await prisma.listings.findUnique({
      where: { id: BigInt(id) }
    });

    if (!currentListing) {
      throw new Error('挂牌信息不存在');
    }

    // 检查用户是否已主动下架
    const isUserOfflined = currentListing.audit_comment === 'USER_OFFLINE';

    const listing = await prisma.listings.update({
      where: { id: BigInt(id) },
      data: {
        audit_status: 'APPROVED',
        audit_admin_id: adminId,
        audit_time: new Date(),
        audit_comment: isUserOfflined
          ? `${comment || '审核通过'}（用户已下架，审核通过但保持下架状态）`
          : comment,
        status: isUserOfflined ? 'OFF_SHELF' : 'ON_SALE', // 用户已下架则保持下架，否则上架
        auto_publish_at: null // 清除自动发布时间
      },
      include: {
        users: {
          select: {
            id: true,
            nickname: true,
            avatar_url: true,
            phone_number: true
          }
        },
        administrators: true
      }
    });
    return new ListingPrisma(listing);
  }

  /**
   * 审核拒绝
   * @param {number} id 挂牌信息ID
   * @param {number} adminId 管理员ID
   * @param {string} comment 审核备注
   * @returns {Promise<ListingPrisma>}
   */
  static async reject(id, adminId, comment = null) {
    // 先查询当前状态，检查用户是否已主动下架
    const currentListing = await prisma.listings.findUnique({
      where: { id: BigInt(id) }
    });

    if (!currentListing) {
      throw new Error('挂牌信息不存在');
    }

    // 检查用户是否已主动下架
    const isUserOfflined = currentListing.audit_comment === 'USER_OFFLINE';

    const listing = await prisma.listings.update({
      where: { id: BigInt(id) },
      data: {
        audit_status: 'REJECTED',
        audit_admin_id: adminId,
        audit_time: new Date(),
        audit_comment: isUserOfflined
          ? `${comment}（用户已下架）`
          : comment,
        status: 'OFF_SHELF', // 审核拒绝后下架（不论用户是否已下架都保持下架）
        auto_publish_at: null // 清除自动发布时间
      },
      include: {
        users: {
          select: {
            id: true,
            nickname: true,
            avatar_url: true,
            phone_number: true
          }
        },
        administrators: true
      }
    });
    return new ListingPrisma(listing);
  }

  /**
   * 获取待审核的挂牌信息列表
   * @param {Object} options 查询选项
   * @returns {Promise<Object>}
   */
  static async getPendingAuditList(options = {}) {
    const { page = 1, pageSize = 10 } = options;

    const pageNum = parseInt(page);
    const pageSizeNum = parseInt(pageSize);
    const skip = (pageNum - 1) * pageSizeNum;

    const [total, listings] = await Promise.all([
      prisma.listings.count({
        where: { audit_status: 'PENDING' }
      }),
      prisma.listings.findMany({
        where: { audit_status: 'PENDING' },
        include: {
          users: {
            select: {
              id: true,
              nickname: true,
              avatar_url: true,
              phone_number: true
            }
          },
          administrators: true
        },
        orderBy: { created_at: 'asc' }, // 按创建时间升序，优先审核早期提交的
        skip,
        take: pageSizeNum
      })
    ]);

    return {
      data: listings.map(listing => new ListingPrisma(listing)),
      pagination: {
        page: pageNum,
        pageSize: pageSizeNum,
        total,
        totalPages: Math.ceil(total / pageSizeNum)
      }
    };
  }

  /**
   * 自动发布超时的挂牌信息（30分钟后自动上架）
   * @returns {Promise<number>} 自动发布的数量
   */
  static async autoPublishExpired() {
    const now = new Date();

    // 使用原始SQL更新,避免Prisma时区转换问题
    const result = await prisma.$executeRaw`
      UPDATE listings
      SET
        audit_status = 'APPROVED',
        status = '在售',
        audit_time = UTC_TIMESTAMP(),
        audit_comment = '系统自动上架（超过30分钟未审核）',
        auto_publish_at = NULL
      WHERE
        audit_status = 'PENDING'
        AND audit_admin_id IS NULL
        AND audit_time IS NULL
        AND (audit_comment IS NULL OR audit_comment != 'USER_OFFLINE')
        AND (
          (auto_publish_at IS NOT NULL AND auto_publish_at <= UTC_TIMESTAMP())
          OR (auto_publish_at IS NULL AND created_at <= DATE_SUB(UTC_TIMESTAMP(), INTERVAL 30 MINUTE))
        )
    `;

    return result;
  }

  /**
   * 获取挂牌统计信息
   * @returns {Promise<Object>}
   */
  static async getStats() {
    const [total, onSale, sold, offShelf] = await Promise.all([
      prisma.listings.count(),
      prisma.listings.count({ where: { status: 'ON_SALE' } }),
      prisma.listings.count({ where: { status: 'SOLD' } }),
      prisma.listings.count({ where: { status: 'OFF_SHELF' } })
    ]);

    return { total, onSale, sold, offShelf };
  }

  /**
   * 转换为JSON对象
   * @returns {Object}
   */
  toJSON() {
    return {
      id: this.id.toString(),
      user_id: this.user_id.toString(),
      listing_type: ListingPrisma.TYPE_REVERSE_MAP[this.listing_type] || this.listing_type,
      company_name: this.company_name,
      status: ListingPrisma.STATUS_REVERSE_MAP[this.status] || this.status,
      price: this.is_negotiable ? null : (this.price ? parseFloat(this.price) : null),
      is_negotiable: this.is_negotiable,
      registration_province: this.registration_province,
      registration_city: this.registration_city,
      establishment_date: this.establishment_date,
      registered_capital_range: ListingPrisma.CAPITAL_RANGE_REVERSE_MAP[this.registered_capital_range] || this.registered_capital_range,
      paid_in_status: ListingPrisma.PAID_STATUS_REVERSE_MAP[this.paid_in_status] || this.paid_in_status,
      company_type: ListingPrisma.COMPANY_TYPE_REVERSE_MAP[this.company_type] || this.company_type,
      tax_status: ListingPrisma.TAX_STATUS_REVERSE_MAP[this.tax_status] || this.tax_status,
      tax_grade: ListingPrisma.TAX_GRADE_REVERSE_MAP[this.tax_grade] || this.tax_grade,
      bank_account_status: ListingPrisma.BANK_STATUS_REVERSE_MAP[this.bank_account_status] || this.bank_account_status,
      has_trademark: this.has_trademark,
      has_patent: this.has_patent,
      has_software_copyright: this.has_software_copyright,
      has_license_plate: this.has_license_plate,
      has_social_security: this.has_social_security,
      bank_flow: this.bank_flow,
      has_bidding_history: this.has_bidding_history,
      description: this.description,
      expires_at: this.expires_at,
      // 审核相关字段
      audit_status: ListingPrisma.AUDIT_STATUS_REVERSE_MAP[this.audit_status] || this.audit_status,
      audit_admin_id: this.audit_admin_id,
      audit_time: this.audit_time,
      audit_comment: this.audit_comment,
      auto_publish_at: this.auto_publish_at,
      created_at: this.created_at,
      updated_at: this.updated_at,
      publisher_nickname: this.publisher_nickname,
      // 包含完整的发布者信息
      publisher: this.users ? {
        id: this.users.id.toString(),
        nickname: this.users.nickname,
        avatar_url: this.users.avatar_url,
        phone_number: this.users.phone_number
      } : null,
      // 为了兼容管理后台，也添加user字段
      user: this.users ? {
        id: this.users.id.toString(),
        nickname: this.users.nickname,
        avatar_url: this.users.avatar_url,
        phone_number: this.users.phone_number
      } : null,
      // 审核管理员信息
      audit_admin: this.audit_admin ? {
        id: this.audit_admin.id,
        username: this.audit_admin.username
      } : null
    };
  }

  /**
   * 统计指定用户在时间区间内发布的挂牌数量
   * @param {number|bigint} userId 用户ID
   * @param {Date} startTime 区间开始时间
   * @param {Date} endTime 区间结束时间
   * @returns {Promise<number>} 发布数量
   */
  static async countUserListingsInRange(userId, startTime, endTime) {
    if (!userId || !startTime || !endTime) {
      return 0;
    }

    const where = {
      user_id: BigInt(userId),
      created_at: {
        gte: startTime,
        lte: endTime
      }
    };

    return prisma.listings.count({ where });
  }
}

module.exports = ListingPrisma;
